function showStatus(message, type) {
    const statusDiv = document.getElementById('statusMessage');
    statusDiv.textContent = message;
    statusDiv.className = `status-message ${type}`;
    statusDiv.style.display = 'block';
    setTimeout(() => {
        statusDiv.style.display = 'none';
    }, 3000);
}

function installPackage(venvName) {
    const packageInput = document.getElementById(`package-input-${venvName}`);
    const package = packageInput.value.trim();
    
    if (!package) {
        showStatus('请输入包名称', 'error');
        return;
    }
    
    fetch(`/venv/install_package/${venvName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `package=${encodeURIComponent(package)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showStatus(data.error, 'error');
        } else {
            showStatus(data.message, 'success');
            // 刷新页面以显示新安装的包
            setTimeout(() => location.reload(), 1000);
        }
    })
    .catch(error => {
        showStatus('安装失败: ' + error, 'error');
    });
}

function uninstallPackage(venvName, packageName) {
    if (!confirm(`确定要卸载 ${packageName} 吗？`)) {
        return;
    }
    
    fetch(`/venv/uninstall_package/${venvName}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `package=${encodeURIComponent(packageName)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showStatus(data.error, 'error');
        } else {
            showStatus(data.message, 'success');
            // 刷新页面以更新包列表
            setTimeout(() => location.reload(), 1000);
        }
    })
    .catch(error => {
        showStatus('卸载失败: ' + error, 'error');
    });
}

// 为包名输入框添加回车键监听
document.addEventListener('DOMContentLoaded', () => {
    const packageInputs = document.querySelectorAll('.package-input');
    packageInputs.forEach(input => {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                const venvName = input.id.replace('package-input-', '');
                installPackage(venvName);
            }
        });
    });
}); 